﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;

namespace YunBox2.DAL
{
    public sealed class DbHelper
    {
        private static readonly ISessionFactory sessionFactory;
        private static ISession currentSession;

        static DbHelper()
        {
            sessionFactory =
                Fluently.Configure(new Configuration()).Mappings(
                    x => x.FluentMappings.AddFromAssembly(typeof(DbHelper).Assembly).ExportTo("d:\\projects\\orm")).
                    BuildSessionFactory();
            //sessionFactory =
            //    Fluently.Configure().Database(
            //        MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("yunbox2")).Dialect
            //            ("NHibernate.Dialect.MsSql2008Dialect").Provider(
            //                "NHibernate.Connection.DriverConnectionProvider").QuerySubstitutions(
            //                    "true 1, false 0, yes 'Y', no 'N'").FormatSql().ShowSql()).Cache(
            //                        c =>
            //                        c.ProviderClass("NHibernate.Cache.HashtableCacheProvider, NHibernate").UseQueryCache
            //                            ()).Mappings(
            //                                x =>
            //                                x.FluentMappings.AddFromAssembly(typeof (DbHelper).Assembly).ExportTo(
            //                                    "d:\\projects\\orm")).BuildSessionFactory();
        }

        public static ISession CreateSession()
        {
            return sessionFactory.OpenSession();
        }

        public static ISession GetCurrentSession()
        {
            if (currentSession == null)
            {
                currentSession = CreateSession();
            }

            return currentSession ?? CreateSession();
        }

        public static void CloseCurrentSession()
        {
            if (currentSession == null)
            {
                // No current session
                return;
            }

            currentSession.Close();
        }

        public static void CloseSessionFactory()
        {
            if (sessionFactory != null)
            {
                sessionFactory.Close();
            }
        }
    }
}